/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.lcfgly.Interceptor;

import com.lcfgly.Database.UserInfo;
import com.lcfgly.Interface.UserSession;
import javax.servlet.http.HttpServletRequest;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * 控制器数据绑定配置
 * 该类用于将session中的登入信息注入到已绑定@UserSession注解的User类数据
 * @author lcfgly
 */
public class SessionArgumentResolver implements HandlerMethodArgumentResolver{

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterAnnotation(UserSession.class) != null;
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        Class<?> klass = parameter.getParameterType();
        if(klass.isAssignableFrom(UserInfo.class)){
            HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
            return (UserInfo)request.getSession().getAttribute("logininfo");
        }
        return mavContainer;
    }
    
}
